//
//  XZPunchCardVC.m
//  Teecloud
//
//  Created by PC on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZPunchCardVC.h"
#import "ZJPickBaseView.h"
#import "ZJDatePickerView.h"
#import "ZJNormalPickerView.h"
#import "XZWorkTimeInfo.h"
#import "XZPunchCardCell.h"
#import "XZPunchCardFootView.h"
#import "XZLeaveApplyDetailVC.h"
#import <AMapLocationKit/AMapLocationKit.h>
@interface XZPunchCardVC ()<UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate>
@property (nonatomic, strong) UIButton *dateBtn;//日期按钮
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) XZPunchCardFootView *footView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, copy) NSString *formattedAddress;
@property (nonatomic, copy) NSString *latitude;
@property (nonatomic, copy) NSString *longitude;
@end

@implementation XZPunchCardVC

- (instancetype)init{
    self = [super init];
    if (self) {
        [self initLocation];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"考勤打卡";
    self.view.backgroundColor = kWhiteColor;
    [self creatRightNav];
    [self getWorkTimeInfo];
    //当地理位置有回调的时候就给footView赋值
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(location:) name:@"LOCATION" object:nil];
}

/**
 监听的回调

 @param noti 携带的经纬度及地址
 */
- (void)location:(NSNotification *)noti{
    NSDictionary *dic = noti.object;
    NSString *la = dic[@"latitude"];
    NSString *log = dic[@"longitude"];
    NSString *address = dic[@"formattedAddress"];
    self.footView.latitude = la;
    self.footView.longitude = log;
    self.footView.formattedAddress = address;
}
/**
 高德定位
 */
- (void)initLocation{
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.locatingWithReGeocode = YES;
    [self.locationManager startUpdatingLocation];
}
//从代理中获取经纬度跟地理信息
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    self.latitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (reGeocode)
    {
        self.formattedAddress =reGeocode.formattedAddress;
        NSLog(@"formattedAddress = %@",reGeocode.formattedAddress);
        
    }
    if (!kIsEmptyString(reGeocode.formattedAddress)) {
        //组装经纬度及位置发送通知
        NSDictionary *dic = @{
                              @"latitude":self.latitude,
                              @"longitude":self.longitude,
                              @"formattedAddress":self.formattedAddress
                              };
        [[NSNotificationCenter defaultCenter]postNotificationName:@"LOCATION" object:dic];
    }
}
#pragma mark - 导航栏右侧日期筛选
- (void)creatRightNav{
    //日期 为空就获取当前的日期
    if (kIsEmptyString(self.queryDate)) {
        NSString *currentDate = [self getCurrentTime];
        self.queryDate = currentDate;
        [self.dateBtn setTitle:currentDate  forState:UIControlStateNormal];
    }else{
        [self.dateBtn setTitle:self.queryDate  forState:UIControlStateNormal];
    }
    UIBarButtonItem *dateItem = [[UIBarButtonItem alloc]initWithCustomView:self.dateBtn];
    self.navigationItem.rightBarButtonItems = @[dateItem];
}

#pragma mark - Networking
- (void)getWorkTimeInfo{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    
    [dict setValue:self.queryDate forKey:@"queryDate"];
    [dict setValue:self.groupId forKey:@"groupId"];
    //如果为空就用当前登录userId
    if (kIsEmptyString(self.memberUserId)) {
       [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"memberUserId"];
    }else{
       [dict setValue:self.memberUserId forKey:@"memberUserId"];
    }
    kWeakObject(self)
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetWorkTimeInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg = [responseObject objectForKey:RESULT_NAME_Message];
                weakself.title = [NSString stringWithFormat:@"考勤打卡-%@",msg];
                [weakself.dataArr removeAllObjects];
                NSArray *array = [XZWorkTimeInfo mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                //先将tableFooterView置空
                weakself.tableView.tableFooterView = [UIView new];
                //IsClockEnable为true就添加footView
                for (XZWorkTimeInfo *model in array) {
                    if (model.IsClockEnable) {
                        weakself.tableView.tableFooterView = weakself.footView;
                        model.groupId = weakself.groupId;
                        weakself.footView.model = model;
                    }
                }
                [weakself.dataArr addObjectsFromArray:array];
                if (weakself.dataArr.count == 0) {
                    [weakself.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tableView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

/**
 footView打卡

 @param dic 参数
 */
- (void)postWorkClockInfo:(NSMutableDictionary *)dic{
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostWorkClockInfo&$v=%@",VERSION] parameters:dic cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                //重新刷新本界面
                [weakself getWorkTimeInfo];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

/**
 选择日期
 
 @param sender 按钮
 */
- (void)dateAction:(UIButton *)sender{
    kWeakObject(self)
    [ZJDatePickerView zj_showDatePickerWithTitle:@"请选择日期" dateType:ZJDatePickerModeYMD defaultSelValue:self.queryDate minDate:nil maxDate:nil isAutoSelect:NO lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
        [weakself.dateBtn setTitle:selectValue forState:UIControlStateNormal];
        weakself.queryDate = selectValue;
        [weakself getWorkTimeInfo];
    } cancelBlock:^{
        
    }];
    
}
/**
 获取当前的日期
 
 @return 日期字符串
 */
- (NSString *)getCurrentTime{
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
    return currentDate;
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZPunchCardCell * cell = [tableView dequeueReusableCellWithIdentifier:@"XZPunchCardCell"];
    XZWorkTimeInfo * model = self.dataArr[indexPath.row];
    cell.model = model;
    //最后一条隐藏线条
    if (indexPath.row == self.dataArr.count- 1) {
        cell.lienView.hidden = true;
        
    }else{
        cell.lienView.hidden = false;
        
    }
    //请假详情
    cell.leaveBlock = ^(XZWorkTimeInfo * _Nonnull model) {
        XZLeaveApplyDetailVC *leaveApplyDetailVC = [[XZLeaveApplyDetailVC alloc]init];
        leaveApplyDetailVC.id = model.ApplyId;
        [weakself.navigationController pushViewController:leaveApplyDetailVC animated:true];
    };
    return cell;
}
#pragma mark - TableViewDelegateWifiName
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120.f;
}
#pragma mark - Setter
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc]init];
    }
    return _dataArr;
}
- (UIButton *)dateBtn{
    if (!_dateBtn) {
        _dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _dateBtn.frame = CGRectMake(0, 0, 100, 30);
        [_dateBtn setImage:[UIImage imageNamed:@"down-white-64"] forState:UIControlStateNormal];
        [_dateBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        _dateBtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
        _dateBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_dateBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -40, 0, 0)];
        [_dateBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
        [_dateBtn addTarget:self action:@selector(dateAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dateBtn;
}
- (XZPunchCardFootView *)footView{
    if (!_footView) {
        kWeakObject(self)
        _footView = [XZPunchCardFootView viewFromXib];
        _footView.frame = CGRectMake(0, 0, kScreenWidth, 200.f);
        _footView.clockTimeBlock = ^(NSMutableDictionary * _Nonnull dict) {
            //打卡
            [weakself postWorkClockInfo:dict];
        };
    }
    return _footView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 10, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight-kBottomSafeHeight-10) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator =false;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        //注册
        [_tableView registerNib:[UINib nibWithNibName:@"XZPunchCardCell" bundle:nil] forCellReuseIdentifier:@"XZPunchCardCell"];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getWorkTimeInfo)];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (void)dealloc{
    self.locationManager.delegate = nil;
    [self.locationManager stopUpdatingLocation];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
